package com.cpecc.controller.excel;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletContext;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.cpecc.manager.wuzi.WuZiManager;
import com.cpecc.model.wuzi.WuZi;

@Controller
@RequestMapping(value = "/wuzi")
public class PanDianDRController implements ServletContextAware{
	
	@Autowired
	private ServletContext servletContext;
	
	@Override
	public void setServletContext(ServletContext context) {
		this.servletContext  = context;
	}
	
	@Autowired
	public WuZiManager wuZiManager;
	
	@RequestMapping(value = "/panDianFuJian")
	public String panDianFuJian(@RequestParam("file") CommonsMultipartFile file){
		String path = this.servletContext.getRealPath("/pandianExcel/");
		String fileName = file.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf("."));		
		String xinName = "";
		String format="yyyyMMdd";
		SimpleDateFormat sdf=new SimpleDateFormat(format);
		String rq=sdf.format(new Date());
		xinName+=rq;
		xinName += new Date().getTime();
		File file2 = new File(path, xinName + fileType);			
		try {
			file.getFileItem().write(file2);				
		} catch (Exception e) {
			e.printStackTrace();
		}
		Workbook book = null;
		try {
			book = Workbook.getWorkbook(file2);
			// 获得第一个工作表对象
			Sheet sheet = book.getSheet(0);
			int rows = sheet.getRows();
			int columns = sheet.getColumns();
			SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// 遍历每行每列的单元格
			for (int i = 1; i < rows; i++) {				
				String ziChanBH=sheet.getCell(0, i).getContents();
				Cell cell = sheet.getCell(columns-1,i);
				WuZi wuZi=wuZiManager.getByZiChanBH(ziChanBH);
				if(wuZi!=null){
					try {
						Date date2=sdf1.parse(cell.getContents());
						wuZi.setPanDianRQ(date2);
					} catch (Exception e) {
						wuZi.setPanDianRQ(new Date());
					}					
					wuZi.setPanDian(4);
					wuZiManager.cover(wuZi);
				}				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (book != null) {
				book.close();
			}
		}
		return "redirect:/wuzi/ziChanPanDian.do";
	}

}
